package com.wechat.page.login;

import java.io.File;
import java.util.List;

import com.swak.fx.support.AbstractComp;
import com.swak.fx.support.AbstractPage;
import com.swak.fx.support.Display;
import com.swak.fx.support.FXMLView;
import com.swak.fx.support.FileChoosers;
import com.swak.fx.support.ui.UI;
import com.swak.fx.support.ui.UIButton;
import com.swak.fx.support.ui.UIIcon;
import com.swak.fx.support.ui.UIImage;
import com.swak.fx.support.ui.UITextField;
import com.swak.utils.FileUtils;
import com.swak.utils.Lists;
import com.wechat.login.LoginService;
import com.wechat.login.NicknameGens;

import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;

/**
 * 用户注册
 * 
 * @author 618lf
 */
@FXMLView(title = "用户注册", value = "UserRegisterComp.fxml", css = "UserRegisterComp.css", stageStyle = "TRANSPARENT")
public class UserRegisterComp extends AbstractComp {

	@FXML
	private UIImage image;
	@FXML
	private UITextField name;
	@FXML
	private UIIcon nameGenBtn;
	@FXML
	private UIButton confirmBtn;
	@FXML
	private Text loginBtn;

	public UserRegisterComp(AbstractPage page) {
		super(page);
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.image.image(Display.logo());
		this.name.setText(NicknameGens.getNickName());
		this.name.setPromptText("请输入用户昵称");
		this.name.setAlignment(Pos.CENTER_LEFT);
		this.nameGenBtn.Icon(UI.Icons.ELLIPSIS_H).size(16);
		this.nameGenBtn.color(UI.Colors.FontXX);
		this.confirmBtn.Success().setText("确定");

		// 不获得输入焦点
		this.name.setDisable(true);
		this.confirmBtn.requestFocus();
		this.$setTimeOut(() -> {
			this.$runOnUI(() -> {
				this.name.setDisable(false);
				this.confirmBtn.requestFocus();
			});
		}, 100);
	}

	@Override
	public void setupEventHandlers() {
		super.setupEventHandlers();
		this.loginBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			this.$emitInPage("page:login");
		});
		this.nameGenBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			String nickname = NicknameGens.getNickName();
			this.name.setText(nickname);
		});
		this.image.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
			List<File> files = FileChoosers.openImageChooser(getWindow());
			if (!Lists.isEmpty(files)) {
				File file = files.get(0);
				byte[] data = FileUtils.read(file);
				this.image.nodeProperty().set(data);
			}
		});
		this.confirmBtn.setOnAction((e) -> {
			try {
				String nickname = this.name.getText();
				byte[] imageData = this.getImageData();
				LoginService.me().create(nickname, imageData);
				this.$emitInPage("page:login");
			} catch (Exception e2) {
			}
		});
	}

	@Override
	public void activated() {
		super.activated();
		this.name.setText(NicknameGens.getNickName());
	}

	private byte[] getImageData() {
		Object imageData = this.image.nodeProperty().get();
		return imageData != null && imageData instanceof byte[] ? (byte[]) imageData : null;
	}
}